<template>
  <Form ref="formRef">
    <template v-for="schema in formSchema" :key="schema">
      <template v-if="schema?.props?.field">
        <template v-if="calcShow(schema)">
          <component
            :is="schema.component"
            v-bind="schema.props"
            v-model="formValue[schema.props.field]"
            @change="
              (record) =>
                schema?.props?.change &&
                schema?.props?.change(record, formValue, formSchema)
            "
          />
        </template>
      </template>
      <component v-else :is="schema.component" v-bind="schema.props" />
    </template>
  </Form>
</template>

<script setup lang="ts">
  import { ref, unref, watch, computed } from 'vue';
  import { Form } from 'vant';

  import type { ItemSchema } from '@/typing/helper';

  const props = defineProps<{
    formSchema: ItemSchema[];
    modelValue: any;
  }>();
  const formValue = ref(props.modelValue);
  const formRef = ref();

  const emits = defineEmits<{
    (e: 'update:modelValue', params: any): void;
    (e: 'submit', params: any): void;
  }>();

  watch(formValue.value, (value) => {
    emits('update:modelValue', unref(value));
  });

  const calcShow = computed(
    () => (schema: ItemSchema) => schema?.props?.show === false ? false : true
  );

  defineExpose({
    // 表单校验
    validate: async () => await formRef.value.validate(),
    // 表单清空
    setValue: function <T>(value: T) {
      formValue.value = value;
    },
  });
</script>

<style lang="less" scoped></style>
